package service

import (
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"guns-go/model/response"
	"guns-go/utils"
)

func OnlineUserPage(onlineUser *request.SysOnlineUserParam, c *gin.Context) (error, *response.PageResult) {

	tempList := make([]*response.SysOnlineUserResult, 0)

	// 获取缓存中的所有用户
	err, sysUserMap := GetCacheAllUser()

	if err != nil {
		return err, nil
	}

	if len(sysUserMap) > 0 {

		for key, user := range sysUserMap {

			sysOnlineUserResult := new(response.SysOnlineUserResult)

			sysOnlineUserResult.SessionId = key
			err = utils.SimpleCopyProperties(sysOnlineUserResult, user)

			if err != nil {
				return err, nil
			}

			tempList = append(tempList, sysOnlineUserResult)
		}
	}

	//TODO 排序

	pageNo, pageSize := utils.GetNoDbPage(c)

	return err, coverToPageResultWithOnlineUser(pageNo, pageSize, len(tempList), tempList)
}

func coverToPageResultWithOnlineUser(pageNo int, pageSize int, totalCount int, r []*response.SysOnlineUserResult) (result *response.PageResult) {

	pageResult := new(response.PageResult)

	rows := make([]interface{}, 0)

	if len(r) > 0 {
		for _, row := range r {
			rows = append(rows, row)
		}
	}

	pageResult.Rows = rows
	pageResult.TotalRows = totalCount
	pageResult.PageNo = pageNo
	pageResult.PageSize = pageSize
	pageResult.TotalPage = (totalCount + pageSize - 1) / pageSize
	pageResult.Rainbow = utils.Rainbow(pageNo, pageResult.TotalPage, global.RainbowNum)

	return pageResult
}

func OnlineUserForceExist(onlineUser *request.SysOnlineUserParam, c *gin.Context) error {

	err, sysUserStr := GetRedisJWTWithString(onlineUser.SessionId)

	user := model.SysUser{}
	err = json.Unmarshal([]byte(sysUserStr), &user)

	if user.Id == 0 {
		return errors.New("该用户已经下线！不要重复操作")
	}

	err = DelRedisJWTWithString(onlineUser.SessionId)

	if err != nil {
		return err
	}

	//创建退出登录日志
	err = ExecuteExitLog(c)

	if err != nil {
		return err
	}

	return nil
}
